<template>
  <div class="center">
    <!-- 头部 -->
    <div class="table_header flex flex_bet flex-wrap">
      <div class="table_button">
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="Refresh"></el-button>
        <!-- <el-button type="success" icon="el-icon-plus" size="small" @click="dialogFormVisible = true">添加</el-button> -->
      </div>
      <div class="table_searchs flex">
        <dynamicTable :checkboxVal="checkboxVal" @alter="alterCheckbok" />
      </div>
    </div>
    <!-- table -->
    <el-table stripe style="width: 100%" :data="browserTable" :key="key" border fit highlight-current-row ref="tableDataRef">
      <!-- <el-table-column v-if="colData[0].istrue" min-width="40" align="center" prop="id" label="ID"></el-table-column> -->
      <el-table-column v-if="colData[0].istrue" min-width="130" align="center" prop="title" label="名称"></el-table-column>
      <el-table-column v-if="colData[1].istrue" min-width="130" align="center" prop="status" label="状态">
        <template slot-scope="scope">
          <div class="state" :class="scope.row.status == '1' ? 'on_line' : 'off_line'">
            <i class="iconfont icon-dian1"></i>
            <span>{{scope.row.status == '1' ? '正常' : '离线'}}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column min-width="80" align="center" prop="log" label="操作">
        <template slot-scope="scope">
          <el-row>
            <el-button size="mini" type="primary" @click="getqueryAuthGroupId(scope.row.id)">编辑</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="paging">
      <el-pagination background :current-page.sync="listQuery.startSize" @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[10, 50, 100, 200]"
        layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="listQuery.pageSize">
      </el-pagination>
    </div>
    <!-- 编辑 -->
    <el-dialog title="编辑" :visible.sync="dialogFormVisible" :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form :model="addForm" ref="ruleForm">
        <el-form-item label="名称" label-width="100px" prop="name">
          <el-input v-model="addForm.title" class="add_select" placeholder="请输入名称" maxlength="30"></el-input>
        </el-form-item>
        <el-form-item label="权限" label-width="100px" prop="name">
          <el-tree ref="tree" :check-strictly="checkStrictly" :data="routesData" :props="defaultProps" show-checkbox node-key="path" class="permission-tree" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false" size="mini" round>取 消</el-button>
        <el-button type="primary" @click="confirmRole" size="mini" round>确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import path from 'path'
import { deepClone } from '@/utils'
import { routerTree } from '@/router/routerTree'
import dynamicTable from "@/components/DynamicTable";
import objectable from "@/utils/objectable.js";
import { queryAuthGroupAll, queryAuthGroupId, updateGroup } from "@/api/infos.js";

const defaultRole = { key: '', name: '', description: '', routes: [] }

const filterName = (data, names) => {
  data.forEach((node => {
    names.push(node.srvName);
    if (node.children && node.children.length) {
      filterName(node.children, names);
    }
  }));
};

export default {
  data() {
    return {
      role: Object.assign({}, defaultRole),
      routes: [],
      checkStrictly: false,
      defaultProps: { children: 'children', label: 'title' },
      checkboxVal: ["名称", "状态"],
      key: 1,
      colData: [], //动态控制table
      //归属table
      browserTable: [],
      total: 0,
      searchTable: "",
      select: "", //搜索条件
      //添加按钮控制
      dialogFormVisible: false,
      //添加表单
      addForm: { title: "", rules: "" },
      subjectId: '',
      listQuery: { startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), type: 1 },
    }
  },
  components: { dynamicTable },
  computed: {
    routesData() {
      return this.routes
    }
  },
  created() {
    this.colData = objectable(this.checkboxVal, this.checkboxVal); //转为数组对象，好控制table
    this.getRoutes()
    this.getqueryAuthGroupAll()
  },
  methods: {
    confirmRole() {
      //this.checkStrictly = false
      const checkedKeys = [].concat(this.$refs.tree.getCheckedKeys(), this.$refs.tree.getHalfCheckedKeys())
      //const checkedKeys = this.$refs.tree.getCheckedKeys()
      this.role.routes = this.generateTree(deepClone(routerTree), '/', checkedKeys)
      // console.log('点击的路由', this.generateTree(deepClone(routerTree), '/', checkedKeys))
      // console.log('点击的路由',  checkedKeys)

      let name = []
      let datas = JSON.parse(JSON.stringify(routerTree))
      filterName(datas, name) //获取当前所有的路由路径
      // console.log(name)
      name.forEach((item, index) => {
        checkedKeys.forEach((value, index1) => {
          if (item == value) { name[index] = 1 }
        })
      })
      name.forEach((item, index) => { if (item != 1) { name[index] = 0 } })
      // console.log('权限配置', name.toString().replace(/,/g, ''))
      let qs = { title: this.addForm.title, rules: name.toString().replace(/,/g, ''), last_ip: sessionStorage.getItem("Ip"), userId: localStorage.getItem("ID"), id: this.subjectId }
      updateGroup(qs).then(res => {
        this.$message.success(res.msg)
        this.getqueryAuthGroupAll()
        this.dialogFormVisible = false
      }).catch(err => { })
    },
    generateTree(routes, basePath = '/', checkedKeys) {
      const res = []
      for (const route of routes) {
        const routePath = path.resolve(basePath, route.path)
        if (route.children) {
          route.children = this.generateTree(route.children, routePath, checkedKeys)
        }
        if (checkedKeys.includes(routePath) || (route.children && route.children.length >= 1)) {
          res.push(route)
        }
      }
      return res
    },
    async getRoutes() {
      this.routes = this.generateRoutes(routerTree)
    },
    // 重新调整路由结构，使其看起来与边栏相同
    generateRoutes(routes, basePath = '/') {
      const res = []
      for (let route of routes) {
        if (route.hidden) { continue }
        const onlyOneShowingChild = this.onlyOneShowingChild(route.children, route)
        if (route.children && onlyOneShowingChild && !route.alwaysShow) {
          route = onlyOneShowingChild
        }
        const data = {
          path: path.resolve(basePath, route.path.trim()),
          title: route.meta && route.meta.title
        }
        // 跳过递归的子路线
        if (route.children) {
          data.children = this.generateRoutes(route.children, data.path)
        }
        res.push(data)
      }
      return res
    },
    onlyOneShowingChild(children = [], parent) {
      let onlyOneChild = null
      const showingChildren = children.filter(item => !item.hidden)
      // 当只有一个子路由时，默认情况下显示子路由
      // if (showingChildren.length === 1) {
      //   onlyOneChild = showingChildren[0]
      //   onlyOneChild.path = path.resolve(parent.path, onlyOneChild.path)
      //   console.log("当只有一个子路由时，默认情况下显示子路由",onlyOneChild,onlyOneChild.patm)
      //   return onlyOneChild
      // }
      // 如果没有子路径显示，则显示父路径
      if (showingChildren.length === 0) {
        onlyOneChild = { ...parent, path: '', noShowingChildren: true }
        return onlyOneChild
      }
      return false
    },
    //根据ID查询信息
    getqueryAuthGroupId(id) {
      this.dialogFormVisible = true
      this.subjectId = id
      this.checkStrictly = true
      queryAuthGroupId({ id: id }).then(res => {
        this.addForm.title = res.data.title
        this.$nextTick(() => {
          const routes = this.generateRoutes(routerTree)//获取路由表
          let roule = res.data.rules.split('').map(item => Number(item))//后台返回的路由字符串，1代表显示，0表示隐藏
          let rue = this.forRoule(roule, this.generateArr(routes))
          // console.log("后台返回的路由信息", roule.length, this.generateArr(routes).length,'------',rue)
          this.$refs.tree.setCheckedNodes(rue)
          this.checkStrictly = false
        })
      })
    },
    forRoule(roule, routes) {
      let data = []
      roule.forEach((item, index) => {
        if (item == 1) {
          data.push(routes[index])
          delete routes[index].children
        }
      });
      return data
    },
    generateArr(routes) {
      let data = []
      routes.forEach(route => {
        data.push(route)
        if (route.children) {
          const temp = this.generateArr(route.children)
          if (temp.length > 0) {
            data = [...data, ...temp]
          }
        }
      })
      return data
    },
    getqueryAuthGroupAll(startSize = 1, pageSize = 10, type = 1) {
      let qs = { startSize: startSize, pageSize: pageSize, type: type, userId: localStorage.getItem("ID") };
      queryAuthGroupAll(this.listQuery).then(res => {
        this.browserTable = res.data
        this.total = res.total
      }).catch(err => {
        this.browserTable = []
      })
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getqueryAuthGroupAll();
    },
    handleCurrentChange(val) {
      this.listQuery.startSize = val
      this.getqueryAuthGroupAll();
    },
    Refresh() {
      this.listQuery = { startSize: 1, pageSize: 10, userId: localStorage.getItem("ID"), type: 1 }
      this.getqueryAuthGroupAll()
    },
    //下拉动态table子组件
    alterCheckbok(key, conte) {
      this.key = key;
      this.colData.filter(i => {
        if (conte.indexOf(i.title) != -1) {
          i.istrue = false;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        } else {
          i.istrue = true;
          this.$nextTick(() => {
            this.$refs.tableDataRef.doLayout();
          });
        }
      });
    }
  }
}
</script>
